<template>
  <div id="questionnaire-index">
    <div class="main-container container-fluid container-limited page-holder">
      <div class="page-title-holder flex content-space-between">
        <h2 class="page-title">我的问卷</h2>
        <div>
          <el-button @click="fillQuestionnaire">填写问卷</el-button>
          <router-link :to="newPath" class="el-button el-button--primary">新建问卷</router-link>
        </div>
      </div>
      <QuestionnairesList :questionnaires="questionnaires" :is-loading="isLoading"/>
      <pagination :current-page="pagination.currentPage" :page-count="pagination.pageCount"/>
    </div>
  </div>
</template>

<script>
import QuestionnairesList from './QuestionnairesList';
import * as format from './format';

export default {
  name: 'QuestionnaireIndex', // 问卷列表
  components: { QuestionnairesList },
  data() {
    return {
      questionnaires: [], // 问卷列表数据
      isLoading: false, // 正在加载列表
      pagination: { // 翻页组件
        currentPage: null, // 当前页
        pageCount: null, // 总页数
      },
    };
  },
  computed: {
    // 前往新建问卷页面
    newPath() { return `/${this.$rp.QUESTIONNAIRES}/${this.$rp.CREATE}`; },
    // 生成加载问卷列表所需参数
    initLoadParams() {
      return {
        page: this.$route.query.page || 1,
      };
    },
  },
  methods: {
    // 加载问卷列表数据
    loadQuestionnaires() {
      this.isLoading = true;
      this.$api.questionnaires.index(this.initLoadParams)
        .then(res => this.handleRes(res))
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
    handleRes(res) {
      this.questionnaires = format.formatQuestionnaires(res.data);
      this.pagination.currentPage = res.kaminari.current_page;
      this.pagination.pageCount = res.kaminari.total_pages;
    },
    // 填写问卷
    fillQuestionnaire() {
      this.$prompt('请输入邀请码', '填写问卷', {
        customClass: 'confirm-left',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => this.$router.push(`/${this.$rp.QUESTIONNAIRES}/${this.$rp.FILL_IN}?qn_key=${value}`))
        .catch(() => {});
    },
  },
  created() { this.loadQuestionnaires(); },
  watch: {
    initLoadParams() { this.loadQuestionnaires(); },
  },
};
</script>

<style></style>
